import { defineStore } from 'pinia';
import apiClient from '@/api/axios';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: JSON.parse(localStorage.getItem('user')) || null,
  }),
  getters: {
    isAuthenticated: (state) => !!state.token,
    userRoles: (state) => state.user?.roles || [],
  },
  actions: {
    /**
     * 用户登录操作
     * @param {object} credentials - 包含 username 和 password 的对象
     * @returns {Promise<{success: boolean, error?: string}>} - 返回一个包含成功状态和可选错误信息的对象
     */
    async login(credentials) {
      try {
        const response = await apiClient.post('/auth/login', credentials);
        const { token, ...userData } = response.data;
        
        this.token = token;
        this.user = userData;
        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(userData));
        
        return { success: true }; // 登录成功
      } catch (error) {
        console.error('Login failed in store:', error);
        this.logout(); // 清理旧状态
        
        // 【核心修正】不再抛出错误，而是返回一个包含错误信息的失败对象
        let errorMessage = '登录时发生未知错误。';
        if (error.response && error.response.status === 401) {
          errorMessage = '用户名或密码不正确，请重试。';
        }
        return { success: false, error: errorMessage };
      }
    },

    logout() {
      this.token = null;
      this.user = null;
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    },
    
    tryAutoLogin() {
      const token = localStorage.getItem('token');
      const user = localStorage.getItem('user');
      if (token && user) {
        this.token = token;
        this.user = JSON.parse(user);
      }
    }
  },
});